//
//  PieChartView.swift
//  bill
//
//  Created by Eudon on 2025/6/18.
//

import SwiftUI

// 立体饼状图视图
struct PieChartView: View {
    var data: [(value: Double, color: Color, label: String)]
    @Binding var selectedIndex: Int?
    
    private var total: Double {
        data.reduce(0) { $0 + $1.value }
    }
    
    private func percentage(for value: Double) -> Double {
        (value / total) * 100
    }
    
    var body: some View {
        VStack(spacing: 25) {
            GeometryReader { geometry in
                let size = min(geometry.size.width, geometry.size.height)
                let center = CGPoint(x: geometry.size.width / 2, y: size / 2)
                
                ZStack {
                    Circle()
                        .fill(Color(UIColor.systemBackground))
                        .frame(width: size * 0.9, height: size * 0.9)
                        .shadow(color: .black.opacity(0.2), radius: 4, x: 0, y: 2)
                        .position(center)
                    
                    ForEach(0..<data.count, id: \.self) { index in
                        PieSlice(startAngle: startAngle(for: index),
                                endAngle: endAngle(for: index),
                                isSelected: selectedIndex == index)
                            .fill(
                                LinearGradient(
                                    gradient: Gradient(colors: [
                                        data[index].color.opacity(0.8),
                                        data[index].color
                                    ]),
                                    startPoint: .top,
                                    endPoint: .bottom
                                )
                            )
                            .overlay(
                                PieSlice(startAngle: startAngle(for: index),
                                        endAngle: endAngle(for: index),
                                        isSelected: selectedIndex == index)
                                    .stroke(Color.white, lineWidth: 1)
                            )
                            .scaleEffect(selectedIndex == index ? 1.05 : 1.0)
                            .shadow(color: .black.opacity(selectedIndex == index ? 0.2 : 0.1),
                                   radius: selectedIndex == index ? 8 : 4,
                                   x: 0,
                                   y: selectedIndex == index ? 4 : 2)
                            .animation(.spring(response: 0.3), value: selectedIndex)
                            .onTapGesture {
                                withAnimation {
                                    selectedIndex = selectedIndex == index ? nil : index
                                }
                            }
                    }
                    
                    Circle()
                        .fill(Color(UIColor.systemBackground))
                        .frame(width: size * 0.5, height: size * 0.5)
                        .position(center)
                        .shadow(color: .black.opacity(0.1), radius: 2, x: 0, y: 1)
                }
                .frame(height: size)
                
                if selectedIndex == nil {
                    VStack(spacing: 8) {
                        Text("总支出")
                            .font(.system(size: 16, weight: .medium))
                            .foregroundColor(Color(.secondaryLabel))
                        Text("¥\(total, specifier: "%.2f")")
                            .font(.system(size: 24, weight: .bold))
                            .foregroundColor(Color(.label))
                    }
                    .position(center)
                } else {
                    VStack(spacing: 6) {
                        Text(data[selectedIndex!].label)
                            .font(.system(size: 16, weight: .semibold))
                            .foregroundColor(Color(.label))
                            .multilineTextAlignment(.center)
                            .lineLimit(2)
                        
                        Text("¥\(data[selectedIndex!].value, specifier: "%.2f")")
                            .font(.system(size: 18, weight: .bold))
                            .foregroundColor(data[selectedIndex!].color)
                        
                        Text("\(percentage(for: data[selectedIndex!].value), specifier: "%.1f")%")
                            .font(.system(size: 14, weight: .medium))
                            .foregroundColor(Color(.secondaryLabel))
                    }
                    .position(center)
                }
            }
            .frame(height: 280)
            
            // 图例列表
            VStack(spacing: 16) {
                ForEach(0..<data.count, id: \.self) { index in
                    HStack(spacing: 12) {
                        Circle()
                            .fill(data[index].color)
                            .frame(width: 12, height: 12)
                        
                        Text(data[index].label)
                            .font(.subheadline)
                        
                        Spacer()
                        
                        Text("\(percentage(for: data[index].value), specifier: "%.1f")%")
                            .font(.subheadline)
                            .foregroundColor(.secondary)
                            .frame(width: 60, alignment: .trailing)
                        
                        Text("¥\(data[index].value, specifier: "%.2f")")
                            .font(.subheadline)
                            .foregroundColor(selectedIndex == index ? data[index].color : .secondary)
                            .frame(width: 100, alignment: .trailing)
                    }
                    .padding(.horizontal, 16)
                    .padding(.vertical, 8)
                    .background(
                        RoundedRectangle(cornerRadius: 8)
                            .fill(selectedIndex == index ? 
                                 data[index].color.opacity(0.1) : 
                                 Color.clear)
                    )
                    .onTapGesture {
                        withAnimation {
                            selectedIndex = selectedIndex == index ? nil : index
                        }
                    }
                }
            }
            .padding(.top, 10)
        }
    }
    
    private func startAngle(for index: Int) -> Angle {
        var start: Double = -90.0
        for i in 0..<index {
            start += (data[i].value / total) * 360
        }
        return .degrees(start)
    }
    
    private func endAngle(for index: Int) -> Angle {
        var end: Double = -90.0
        for i in 0...index {
            end += (data[i].value / total) * 360
        }
        return .degrees(end)
    }
}

struct PieSlice: Shape {
    var startAngle: Angle
    var endAngle: Angle
    var isSelected: Bool
    
    var animatableData: AnimatablePair<Double, Double> {
        get { AnimatablePair(startAngle.degrees, endAngle.degrees) }
        set {
            startAngle = .degrees(newValue.first)
            endAngle = .degrees(newValue.second)
        }
    }
    
    func path(in rect: CGRect) -> Path {
        let center = CGPoint(x: rect.midX, y: rect.midY)
        let radius = min(rect.width, rect.height) / 2 * (isSelected ? 1.0 : 0.95)
        
        var path = Path()
        path.move(to: center)
        path.addArc(center: center,
                   radius: radius,
                   startAngle: startAngle,
                   endAngle: endAngle,
                   clockwise: false)
        path.closeSubpath()
        return path
    }
}

#Preview {
    PieChartView(
        data: [
            (value: 30.0, color: .blue, label: "餐饮"),
            (value: 20.0, color: .red, label: "交通"),
            (value: 15.0, color: .green, label: "购物")
        ],
        selectedIndex: .constant(nil)
    )
    .frame(height: 300)
    .padding()
} 